package interfaces.ltu;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.util.FloatMath;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ImageView.ScaleType;
import android.widget.ZoomControls;


import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;

public class DisplayLocationActivity extends Activity implements OnTouchListener{

	EditText inputUrl;
	String myAddress;
	String ServerIPAddress="130.240.98.130";
	//String ServerIPAddress="130.240.97.145";
	
	//String ServerIPAddress="192.168.0.103";
	public ImageView imgView;
	public float scaleWidth, scaleHeight;
	public float zoom = 0.0f;
	public int  screenWidth=0;
	static float centerX =0, centerY = 0;
	String ClassRoomNum="";
	private static final String TAG = "Touch";
	   // These matrices will be used to move and zoom image
	   Matrix matrix = new Matrix();
	   Matrix savedMatrix = new Matrix();
	   ProgressDialog dialog ;
	   // We can be in one of these 3 states
	   static final int NONE = 0;
	   static final int DRAG = 1;
	   static final int ZOOM = 2;
	   int mode = NONE;

	   // Remember some things for zooming
	   PointF start = new PointF();
	   PointF mid = new PointF();
	   float oldDist = 1f;

	
	OnClickListener getImageBtnOnClick = new OnClickListener() {
		public void onClick(View view) {
			
			
            /*dialog.setMessage("Please wait while loading...");
            dialog.setIndeterminate(true);
            dialog.setCancelable(true);*/
			ServerCom sc =new ServerCom();
			sc.execute(ClassRoomNum);
//			s
			//roomListSpinner.getSelectedItemPosition()
			//roomListSpinner.
			
			
			ZoomControls myImageControllers= (ZoomControls)findViewById(R.id.zoomControls1);
			myImageControllers.setOnZoomInClickListener(new View.OnClickListener() {
	              
	                public void onClick(View v) {
                        //v= imgView;
                        System.out.println("ZoomIN");
                        ZoomIn();
	                }});
			myImageControllers.setOnZoomOutClickListener(new View.OnClickListener() {
	              
	                public void onClick(View v) {
	                      //v= imgView;
	                      System.out.println("ZoomOut");
	                      ZoomOut();
	                }
	        });
		}
	};

	/** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.displaylocationbuttonmain);
     // Request for the progress bar to be shown in the title
        //requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        /*dialog = new ProgressDialog(this);
        dialog.setMessage("Please wait while loading...");
        dialog.setIndeterminate(false);
        dialog.setCancelable(true);*/
	
        imgView = (ImageView) findViewById(R.id.image1);// this is for inst.
		imgView.setOnTouchListener(this);
    
		inputUrl = ((EditText) findViewById(R.id.imageUrl));// this is for inst.
		inputUrl.setSingleLine();
		inputUrl.setTextSize(11);
		
        ImageButton next = (ImageButton) findViewById(R.id.DisplayLocationbackButton);
        next.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent intent = new Intent();
                setResult(RESULT_OK, intent);
                finish();
            }

        });
    
		Button getImageButton = (Button) findViewById(R.id.getImageButton);// this
		// too
		getImageButton.setOnClickListener(getImageBtnOnClick);

		final Spinner roomListSpinner = (Spinner) findViewById(R.id.spinner1);

		List<String> roomNumberList = new ArrayList<String>();
		/*HashSet<String> ClassRoomS=AccessAndroidCalender.getCalender(this);
		for (String id : ClassRoomS)
		{
			roomNumberList.add(id);
			System.out.println("ClassID "+id);
		}*/
		
		roomNumberList.add("A1503");
		roomNumberList.add("A1504");
		roomNumberList.add("A1506");
		ArrayAdapter<String> aspnMusketeers = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, roomNumberList);

		aspnMusketeers.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		roomListSpinner.setAdapter(aspnMusketeers);

		// Set up a callback for the spinner
		roomListSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onNothingSelected(AdapterView<?> arg0) {
			}

			public void onItemSelected(AdapterView<?> parent, View v,
					int position, long id) {
				// Code that does something when the Spinner room number is
				// changed
				ClassRoomNum=roomListSpinner.getSelectedItem().toString();
				Log.d(TAG,roomListSpinner.getSelectedItem().toString());
				//Toast.makeText(this, roomListSpinner.getSelectedItem().toString(),2000).show();
				int position0 = 0;
				int position1 = 1;
				int position2 = 2;
				int position3 = 3;
				int position4 = 4;

				if (position4 == roomListSpinner.getSelectedItemPosition()) {
					myAddress = "http://bishopsworth.wikispaces.com/file/view/Planets_shirt_2_large.jpg/52134137/Planets_shirt_2_large.jpg";

				}
				if (position3 == roomListSpinner.getSelectedItemPosition()) {
					myAddress = "http://spaceplace.nasa.gov/planet-weather/8_planets.en.jpg";

				}
				if (position2 == roomListSpinner.getSelectedItemPosition()) {
					myAddress = "http://www.manatee.k12.fl.us/sites/elementary/samoset/psgk3ex_files/Neptune.gif";

				}
				if (position1 == roomListSpinner.getSelectedItemPosition()) {
					myAddress = " http://upload.wikimedia.org/wikipedia/commons/thumb/3/3e/1e7m_comparison_Uranus_Neptune_Sirius_B_Earth_Venus.png/300px-1e7m_comparison_Uranus_Neptune_Sirius_B_Earth_Venus.png";

				}
				if (position0 == roomListSpinner.getSelectedItemPosition()) {
					myAddress = " http://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Exoplanet_Comparison_HR_8799_c.png/320px-Exoplanet_Comparison_HR_8799_c.png";

				}

			}
			//
		});
	}

	private Drawable ImageOperations(Context ctx, String url,
			String saveFilename) {
		try {
			InputStream is = (InputStream) this.fetch(url);
			Drawable d = Drawable.createFromStream(is, "src");
			return d;
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	public Object fetch(String address) throws MalformedURLException,
	IOException {
		// myAddress="http://image.gsfc.nasa.gov/image/image_launch_a5.jpg";
		address = myAddress;
		URL url = new URL(address);
		Object content = url.getContent();
		return content;
	}

	public class ServerCom extends AsyncTask<String, Integer, Bitmap>{

		@Override
		protected Bitmap doInBackground(String... arg0) {
			// TODO Auto-generated method stub
			Bitmap bmp = null;
			Socket socket= null;
			try {
				
				//socket= new Socket(ServerIPAddress,9001);
				socket= new Socket(ServerIPAddress,8890);
				//socket.setSoTimeout(8000) ;
				
				//PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
				ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
				Log.d(TAG,arg0[0]);
				out.writeObject(arg0[0]);
				//out.println(arg0[0]);
				out.flush();
				System.out.println("MSg sent");
				ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
				byte[] buffer;
				
				try {
					
					buffer = (byte[])ois.readObject();
					//FileOutputStream fos = new FileOutputStream("/sdcard/tlogo1.jpg");
					//fos.write(buffer);
					//fos.close();
					System.out.println("MSg Write to file");
					 bmp=BitmapFactory.decodeByteArray(buffer,0,buffer.length);
					//ImageView image=new ImageView(this);
			        // icon.setImageBitmap(bmp);
					 System.out.println("MSg Received");
					 socket.close();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return bmp;
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			//((ImageView) imgView).setImageBitmap(result);
			//float scaleWidth, scaleHeight;
			Display display = getWindowManager().getDefaultDisplay(); 
			screenWidth = display.getWidth();
			//int screenHeight = display.getHeight();
			ShowImage(result);
			/*float imageWidth = (float)result.getWidth();
			float imageHeight = (float)result.getHeight();
			float newHeight = imageHeight / (imageWidth / screenWidth);
			float newWidth = screenWidth;
			scaleWidth = screenWidth / imageWidth;
			scaleHeight = newHeight / imageHeight;
			imgView.setImageBitmap(result);
			Matrix mtrx = new Matrix();
			mtrx.postScale(scaleWidth, scaleHeight);
			imgView.setImageMatrix(mtrx);
			imgView.setScaleType(ScaleType.MATRIX);
			imgView.invalidate();*/
		}

	}
	void ShowImage(Bitmap cur_bm) {
		//Bitmap cur_bm = BitmapFactory.decodeFile(path);
		float imageWidth = (float)cur_bm.getWidth();
		float imageHeight = (float)cur_bm.getHeight();
		float newHeight = imageHeight / (imageWidth / screenWidth);
		float newWidth = screenWidth;
		scaleWidth = screenWidth / imageWidth;
		scaleHeight = newHeight / imageHeight;
		imgView.setImageBitmap(cur_bm);
		SetImageMatrix();

	}
	
	void SetImageMatrix() {
		Matrix mtrx = new Matrix();
		mtrx.postScale(scaleWidth, scaleHeight);
		imgView.setImageMatrix(mtrx);
		imgView.setScaleType(ScaleType.MATRIX);
		imgView.invalidate();

		}

		void ZoomIn() {
		zoom += 0.01;
		scaleWidth += zoom;
		scaleHeight += zoom;
		System.out.println("ZoomIn  scaleWidth:"+scaleWidth+" scaleHeight:"+scaleHeight+ " zoom:"+zoom);
		SetImageMatrix();

		}

		void ZoomOut() {
		zoom -= 0.01;
		scaleWidth -= zoom;
		scaleHeight -= zoom;
		System.out.println("ZoomOut scaleWidth:"+scaleWidth+" scaleHeight:"+scaleHeight+ " zoom:"+zoom);
		SetImageMatrix();
		} 

	
	/**/
		public boolean onTouch(View v, MotionEvent event) {
		      ImageView view = (ImageView) v;

		      // Dump touch event to log
		      dumpEvent(event);

		      // Handle touch events here...
		      switch (event.getAction() & MotionEvent.ACTION_MASK) {
		      case MotionEvent.ACTION_DOWN:
		         savedMatrix.set(matrix);
		         start.set(event.getX(), event.getY());
		         Log.d(TAG, "mode=DRAG");
		         mode = DRAG;
		         break;
		      case MotionEvent.ACTION_POINTER_DOWN:
		         oldDist = spacing(event);
		         Log.d(TAG, "oldDist=" + oldDist);
		         if (oldDist > 10f) {
		            savedMatrix.set(matrix);
		            midPoint(mid, event);
		            mode = ZOOM;
		            Log.d(TAG, "mode=ZOOM");
		         }
		         break;
		      case MotionEvent.ACTION_UP:
		      case MotionEvent.ACTION_POINTER_UP:
		         mode = NONE;
		         Log.d(TAG, "mode=NONE");
		         break;
		      case MotionEvent.ACTION_MOVE:
		         if (mode == DRAG) {
		            // ...
		            matrix.set(savedMatrix);
		            matrix.postTranslate(event.getX() - start.x,
		                  event.getY() - start.y);
		         }
		         else if (mode == ZOOM) {
		            float newDist = spacing(event);
		            Log.d(TAG, "newDist=" + newDist);
		            if (newDist > 10f) {
		               matrix.set(savedMatrix);
		               float scale = newDist / oldDist;
		               matrix.postScale(scale, scale, mid.x, mid.y);
		            }
		         }
		         break;
		      }

		      view.setImageMatrix(matrix);
		      return true; // indicate event was handled
		   }

		   /** Show an event in the LogCat view, for debugging */
		   private void dumpEvent(MotionEvent event) {
		      String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE",
		            "POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
		      StringBuilder sb = new StringBuilder();
		      int action = event.getAction();
		      int actionCode = action & MotionEvent.ACTION_MASK;
		      sb.append("event ACTION_").append(names[actionCode]);
		      if (actionCode == MotionEvent.ACTION_POINTER_DOWN
		            || actionCode == MotionEvent.ACTION_POINTER_UP) {
		         sb.append("(pid ").append(
		               action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
		         sb.append(")");
		      }
		      sb.append("[");
		      for (int i = 0; i < event.getPointerCount(); i++) {
		         sb.append("#").append(i);
		         sb.append("(pid ").append(event.getPointerId(i));
		         sb.append(")=").append((int) event.getX(i));
		         sb.append(",").append((int) event.getY(i));
		         if (i + 1 < event.getPointerCount())
		            sb.append(";");
		      }
		      sb.append("]");
		      Log.d(TAG, sb.toString());
		   }

		   /** Determine the space between the first two fingers */
		   private float spacing(MotionEvent event) {
		      float x = event.getX(0) - event.getX(1);
		      float y = event.getY(0) - event.getY(1);
		      return FloatMath.sqrt(x * x + y * y);
		   }

		   /** Calculate the mid point of the first two fingers */
		   private void midPoint(PointF point, MotionEvent event) {
		      float x = event.getX(0) + event.getX(1);
		      float y = event.getY(0) + event.getY(1);
		      point.set(x / 2, y / 2);
		   }
		   /**/
}
